﻿using ApiModel;
using SqlSugar;
using WebUtils;
using WebModel.Entitys;
using WebUtils.BaseService;
using WebUtils.HttpContextUser;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

namespace MainCore.Controllers
{
	/// <summary>
	/// @($"{Model.EntityName}Controller")
	/// </summary>
    [Authorize]
    [ApiController]
	[Route("api/[controller]/[action]")]
	public class @($"{Model.EntityName}Controller") : ControllerBase
    {
        #region IOC&DI
        private readonly @($"IBaseService<{Model.EntityName}>") _service;
		private readonly IUser _user;

        public @($"{Model.EntityName}Controller") (@($"IBaseService<{Model.EntityName}>") service,IUser user)
		{
			_service = service;
			_user = user;
		}
        #endregion

		#region 获取数据
		/// <summary>
		/// 获取数据列表
		/// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ContentJson> GetList([FromBody] Pagination page)
		{
			var exp = Expressionable.Create<@Model.EntityName>();
            exp = exp.Add(t => !t.IsDelete);
			// 增加查询条件
			return new ContentJson
            {
				msg = "success",
				success = true,
				data = await _service.QueryPage(page,exp.ToExpression())
			};
		}

        /// <summary>
		/// 获取数据列表, 作为选项
		/// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ContentJson> GetOption()
		{
			var exp = Expressionable.Create<@Model.EntityName>();
            exp = exp.Add(t => !t.IsDelete);
			// 增加查询条件
			return new ContentJson
            {
				msg = "success",
				success = true,
                data = await _service.Query(t => new @Model.EntityName { Id = t.Id, Name = t.Name }, exp.ToExpression(), t => t.Sort);
			};
		}

		/// <summary>
		/// 获取实体
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<ContentJson> GetEntity([FromBody] object id)
		{
			var exp = Expressionable.Create<@Model.EntityName>();
			// 增加查询条件
			var entity = await _service.QueryById(id);
			return new ContentJson
			{
				msg = "success",
				success = true,
				data = entity
			};
		}
		#endregion

		#region 提交数据
		/// <summary>
		/// 新增或更新实体
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<ContentJson> Save([FromBody] @Model.EntityName entity)
		{
			var res = new ContentJson("保存失败");
			if (await _service.Storageable(entity) > 0)
			{
                res = new ContentJson(true, "保存成功", entity);
			}
			return res;
		}

		/// <summary>
		/// 删除实体
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<ContentJson> Delete([FromQuery] string Id)
		{
			//结果定义
			var res = new ContentJson("删除失败");
            if(await _service.DeleteById(Id)) res = new ContentJson(true, "删除成功");
			return res;
		}
		#endregion
	}
}
